from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional, Any
from pydantic import BaseModel
from datetime import datetime

from db.database import get_db
from services import formula_service, submission_service


router = APIRouter()


# Pydantic models for request/response
class FormulaCreate(BaseModel):
    latex: str


class FormulaUpdate(BaseModel):
    latex: str


class FormulaResponse(BaseModel):
    id: int
    latex: str
    created_at: str

    model_config = {"from_attributes": True}


class SubmissionResponse(BaseModel):
    id: int
    formula_id: int
    image_path: str
    status: str
    ocr_result: Optional[str]
    created_at: str
    formula: Optional[FormulaResponse]

    model_config = {"from_attributes": True}


class SubmissionListResponse(BaseModel):
    submissions: List[SubmissionResponse]
    total: int
    skip: int
    limit: int


class SubmissionStatusUpdate(BaseModel):
    status: str
    ocr_result: Optional[str] = None


# Submission management endpoints
@router.get("/submissions")
def get_submissions(
    skip: int = Query(0, ge=0, description="Number of records to skip"),
    limit: int = Query(100, ge=1, le=1000, description="Maximum number of records to return"),
    formula_id: Optional[int] = Query(None, description="Filter by formula ID"),
    status: Optional[str] = Query(None, description="Filter by status"),
    db: Session = Depends(get_db)
):
    """Get a list of submissions with pagination and filtering support."""
    submissions = submission_service.get_submissions(
        db, skip=skip, limit=limit, formula_id=formula_id, status=status
    )
    total = submission_service.get_submissions_count(db, formula_id=formula_id, status=status)

    result_submissions = []
    for sub in submissions:
        sub_data = {
            "id": sub.id,
            "formula_id": sub.formula_id,
            "image_path": sub.image_path,
            "status": sub.status,
            "ocr_result": sub.ocr_result,
            "created_at": sub.created_at.isoformat() if sub.created_at else None,
            "formula": None
        }
        if sub.formula:
            sub_data["formula"] = {
                "id": sub.formula.id,
                "latex": sub.formula.latex,
                "created_at": sub.formula.created_at.isoformat() if sub.formula.created_at else None
            }
        result_submissions.append(sub_data)

    return {
        "submissions": result_submissions,
        "total": total,
        "skip": skip,
        "limit": limit
    }


@router.get("/submissions/{submission_id}")
def get_submission(submission_id: int, db: Session = Depends(get_db)):
    """Get a single submission by its ID."""
    submission = submission_service.get_submission_by_id(db, submission_id)
    if not submission:
        raise HTTPException(status_code=404, detail="Submission not found")

    result = {
        "id": submission.id,
        "formula_id": submission.formula_id,
        "image_path": submission.image_path,
        "status": submission.status,
        "ocr_result": submission.ocr_result,
        "created_at": submission.created_at.isoformat() if submission.created_at else None,
        "formula": None
    }
    if submission.formula:
        result["formula"] = {
            "id": submission.formula.id,
            "latex": submission.formula.latex,
            "created_at": submission.formula.created_at.isoformat() if submission.formula.created_at else None
        }
    return result


@router.put("/submissions/{submission_id}")
def update_submission_status(
    submission_id: int,
    update_data: SubmissionStatusUpdate,
    db: Session = Depends(get_db)
):
    """Update submission status and OCR result."""
    submission = submission_service.get_submission_by_id(db, submission_id)
    if not submission:
        raise HTTPException(status_code=404, detail="Submission not found")

    # 更新状态
    submission.status = update_data.status
    if update_data.ocr_result is not None:
        submission.ocr_result = update_data.ocr_result

    db.commit()
    db.refresh(submission)

    return {"success": True, "message": "Submission updated successfully"}


# Formula management endpoints
@router.get("/formulas")
def get_formulas(db: Session = Depends(get_db)):
    """Get all formulas."""
    formulas = formula_service.get_all_formulas(db)
    result = []
    for formula in formulas:
        result.append({
            "id": formula.id,
            "latex": formula.latex,
            "created_at": formula.created_at.isoformat() if formula.created_at else None
        })
    return result


@router.post("/formulas")
def create_formula(formula: FormulaCreate, db: Session = Depends(get_db)):
    """Create a new formula."""
    new_formula = formula_service.create_formula(db, formula.latex)
    return {
        "id": new_formula.id,
        "latex": new_formula.latex,
        "created_at": new_formula.created_at.isoformat() if new_formula.created_at else None
    }


@router.put("/formulas/{formula_id}")
def update_formula(formula_id: int, formula: FormulaUpdate, db: Session = Depends(get_db)):
    """Update an existing formula."""
    updated_formula = formula_service.update_formula(db, formula_id, formula.latex)
    if not updated_formula:
        raise HTTPException(status_code=404, detail="Formula not found")
    return {
        "id": updated_formula.id,
        "latex": updated_formula.latex,
        "created_at": updated_formula.created_at.isoformat() if updated_formula.created_at else None
    }


@router.delete("/formulas/{formula_id}")
def delete_formula(formula_id: int, db: Session = Depends(get_db)):
    """Delete a formula by its ID."""
    success = formula_service.delete_formula(db, formula_id)
    if not success:
        raise HTTPException(status_code=404, detail="Formula not found")
    return {"message": "Formula deleted successfully"}
